package se.energimyndigheten.lampguiden.conversiontable;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import org.json.JSONException;

import java.io.IOException;
import java.util.Map;

import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

public class ConversionFragment extends android.support.v4.app.Fragment {

	private static String HTML_BASEPATH = "";
	private static final String TAG = ConversionFragment.class.getSimpleName();
	private static final String HELP_PATH = HTML_BASEPATH + "Help/sv_Conversion.html";

	private WebView mWebView;
	private Map<Integer, String> mTable;
	private Map<Integer, String> mTableR12;
	private Map<Integer, String> mTableR230;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
		return inflater.inflate(R.layout.conversion_activity, container, false);
	}

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		FragmentActivity parent = this.getActivity();
		try {
			mTable = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(parent.getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE), "classic");
			mTableR12 = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(parent.getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE), "halogen_gu53");
			mTableR230 = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(parent.getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE), "halogen_gu10");
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mWebView = (WebView) parent.findViewById(R.id.webview);

		String html = "";
		// parse HTML and insert data at placeholder
		try {
			html = AssetsUtil.getFileContents(parent.getAssets(), AssetsUtil.HTML_PATH_CONVERSION_TABLE);
			AssetsUtil.getParsedConversionTable(mTable);
			html = html.replace(AssetsUtil.HTML_PLACEHOLDER, AssetsUtil.getParsedConversionTable(mTable));
			html = html.replace(AssetsUtil.HTML_PLACEHOLDER_R12, AssetsUtil.getParsedConversionTable(mTableR12));
			html = html.replace(AssetsUtil.HTML_PLACEHOLDER_R230, AssetsUtil.getParsedConversionTable(mTableR230));
		} catch (IOException e) {
			Log.e(TAG, "IOException catch reading html.");
			e.printStackTrace();
		}
		mWebView.loadDataWithBaseURL("file:///android_asset/" + AssetsUtil.HTML_PATH_CONVERSION_TABLE, html, "text/html", "UTF-8", null);
	}
}
